package response

import (
	"github.com/gogf/gf/net/ghttp"
	"github.com/strugglerx/sjson"
)

// 定义错误状态
const (
	Success          = 0    //成功 0
	ClientError      = 6401 //客户端错误
	ServiceError     = 6500 //服务异常
	ServerSqlError   = 6501 //数据服务异常
	ServerRedisError = 6502 //数据服务异常
)

type JsonRes struct {
	Code     int         `json:"code"`
	Data     interface{} `json:"data,omitempty"`
	Message  string      `json:"msg,omitempty"`
	Redirect string      `json:"redirect,omitempty"`
}

func stateString(state int) string {
	var stateDesc = "未知"
	switch state {
	case Success:
		stateDesc = "成功"
	case ClientError:
		stateDesc = "客户端错误"
	case ServiceError, ServerSqlError, ServerRedisError:
		stateDesc = "服务异常"
	}
	return stateDesc
}

// 纠正存在类型为string 实际是json的数据
func writeStringJson(r *ghttp.Request, jsonRes JsonRes) {
	r.Response.Header().Set("Content-Type", "application/json")
	r.Response.Write(sjson.StringWithJsonSafetyRegexToString(jsonRes))
}

// 返回标准JSON数据。
func Json(r *ghttp.Request, code int, message string, data ...interface{}) {
	var responseData interface{}
	withJson := false
	for _, v := range data {
		switch v.(type) {
		case bool:
			withJson = v.(bool)
		case interface{}:
			responseData = v
		}
	}
	if responseData == nil && message == "" {
		responseData = stateString(code)
	}
	if !withJson {
		r.Response.WriteJson(JsonRes{
			Data:    responseData,
			Code:    code,
			Message: message,
		})
		return
	}
	writeStringJson(r, JsonRes{
		Data:    responseData,
		Code:    code,
		Message: message,
	})
}

func JsonExit(r *ghttp.Request, code int, message string, data ...interface{}) {
	Json(r, code, message, data...)
	r.Exit()
}

func JsonDefaultExit(r *ghttp.Request, data interface{}, err error, withUnmarshalJson ...bool) {
	if err != nil {
		JsonExit(r, ServiceError, err.Error(), nil)
	}
	withJson := false
	if len(withUnmarshalJson) > 0 {
		withJson = withUnmarshalJson[0]
	}
	JsonExit(r, Success, "", data, withJson)
}
